/*
 * OPIAM Suite
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

package opiam.admin.applis.demo.actions;

import opiam.admin.applis.demo.beans.Person;
import opiam.admin.faare.MessageUtil;
import opiam.admin.faare.service.UserContext;
import opiam.admin.faare.service.services.SortService;
import opiam.admin.faare.struts.actions.SecureAction;
import opiam.admin.faare.struts.utils.SessionContext;

import org.apache.commons.beanutils.PropertyUtils;

import org.apache.log4j.Logger;

import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import java.io.IOException;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * This action allows to add in the temporary list a selected subset of users.
 * 
 * HTTP PARAMETERS :<br>
 * <li>cartname : target list name</li>
 * <li>srcname  : source object name</li>
 * <li>srcproperty : attribute containing list in source object, or null if the source object is the list</li>
 * <li>eltindex : multivalued elements indexes</li>
 *
 */
public class AddToCartAction extends SecureAction
{
    /** Logger de log4j. */
    private static Logger _logger = Logger.getLogger(AddToCartAction.class);

    /**
     * Struts Action method.
     * See SecureAction
     *
     * @param mapping Struts mapping data.
     * @param actionForm Input form.
     * @param request HTTP request.
     * @param httpServletResponse HTTP response.
     *
     * @return forward to success or to error
     *
     * @throws java.io.IOException see Action.execute()
     * @throws javax.servlet.ServletException see Action.execute()
     */
    @Override
	public ActionForward secureExecute(
        ActionMapping mapping,
        ActionForm actionForm,
        HttpServletRequest request,
        HttpServletResponse httpServletResponse)
        throws IOException, ServletException
    {
        String cartname = request.getParameter("cartname");
        String srcname = request.getParameter("srcname");
        String srcproperty = request.getParameter("srcproperty");
        String[] elements = request.getParameterValues("eltindex");

        if (elements == null)
        {
            // no selection
            request.setAttribute("cartname", cartname);

            return (mapping.findForward("success"));
        }

        _logger.debug("cartname = " + cartname);
        _logger.debug("srcname = " + srcname);
        _logger.debug("srcproperty = " + srcproperty);

        ActionMessages errors = new ActionMessages();

        if ((cartname == null) || cartname.trim().equals("") ||
            (srcname == null) || srcname.trim().equals(""))
        {
            _logger.error(MessageUtil.getMessageString("MSG_ARGUMENT_NULL"));
            errors.add(ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage("error.service.unknown"));
            saveErrors(request, errors);

            return (mapping.findForward("service_error"));
        }

        SessionContext sessionContext = null;
        UserContext userContext = null;

        try
        {
            // Gets the session.
            HttpSession session = request.getSession();
            // Gets the session context.
            sessionContext = SessionContext.getInstance(session);
            // Gets the user context.
            userContext = sessionContext.getUserContext();

            List currentCart = (List) session.getAttribute(cartname);

            if (currentCart == null)
            {
                // new cart
                _logger.debug("cart " + cartname + " is null, will be created");
                currentCart = new ArrayList();
                session.setAttribute(cartname, currentCart);
            }

            Object objSource = session.getAttribute(srcname);
            _logger.debug("objSource class = " + objSource.getClass());

            List currentSrc = null;

            if (srcproperty == null)
            {
                currentSrc = (List) objSource;
            }
            else
            {
                currentSrc = (List) PropertyUtils.getProperty(objSource,
                        srcproperty);
            }

            Object obj = null;

            for (int i = 0; i < elements.length; i++)
            {
                obj = currentSrc.get(Integer.parseInt(elements[i]));

                if (!currentCart.contains(obj))
                {
                    currentCart.add(obj);
                }
            }
            
            // Sorts the list
            SortService.sort(currentCart, Person.class, "name", userContext);
            // Puts the list in the request
            request.setAttribute("cartname", cartname);
            
            // Manages the display of the tempList icon
            boolean indic = userContext.getParameters().containsKey("cartIndic");
            if (!indic)
            {
            	userContext.getParameters().put("cartIndic", "cartname");
            }

            return (mapping.findForward("success"));
        }
        catch (Exception se)
        {
            _logger.debug("Trace", se);
            _logger.error(se.getMessage());
            errors.add(ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage("error.service.unknown"));
            saveErrors(request, errors);

            return (mapping.findForward("error"));
        }
    }
}
